package cn.it.shop.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import cn.it.shop.dao.AccountDao;
import cn.it.shop.dao.BaseDao;
import cn.it.shop.dao.CategoryDao;
import cn.it.shop.dao.ForderDao;
import cn.it.shop.dao.GoodsDao;
import cn.it.shop.dao.PrivilegeDao;
import cn.it.shop.dao.RoleDao;
import cn.it.shop.dao.SorderDao;
import cn.it.shop.dao.UserDao;
import cn.it.shop.service.BaseService;

/*
 * 公共业务逻辑实现类,所有业务逻辑继承此类,则不需要在写公共的逻辑实现
 * */
@SuppressWarnings("unchecked")
@Service(value = "baseService")
/* value="baseService" 对于 bean id,如果不写则默认为类名(第一个字母小写) */
@Lazy(true)
// 省略value属性
public class BaseServiceImpl<T> implements BaseService<T> {

	private Class clazz; // clazz就是要操作的类型, 例如Account Category
	// 此Dao是不能直接实例化的
	public BaseDao baseDao;
	@Resource
	public AccountDao accountDao;
	@Resource
	public CategoryDao categoryDao;
	@Resource
	public ForderDao forderDao;
	@Resource
	public GoodsDao goodsDao;
	@Resource
	public PrivilegeDao privilegeDao;
	@Resource
	public RoleDao roleDao;
	@Resource
	public SorderDao sorderDao;
	@Resource
	public UserDao userDao;

	public BaseServiceImpl() {
		System.out.println("accountDao=" + accountDao);
		System.out.println("BaseServiceImpl()");
		ParameterizedType type = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}
	
	@PostConstruct
	public void init() throws Exception{
		// this代表当前子对象
		// 1:获取clazz相关类简单名称    Category Account  Goods
		String simpleName = clazz.getSimpleName();
		// 2: 第一个字母转小写 然后在加上 "Dao"   categoryDao  accountDao goodsDao
		String daoName=simpleName.substring(0,1).toLowerCase() + simpleName.substring(1) + "Dao";
		// 3: 利用名称通过反射机制, 获取相应Field,然后吧获取的Field字段给 baseDao
		Field daoField=this.getClass().getField(daoName);
//		baseField.set(this, daoField.get(this));
		this.baseDao=(BaseDao)daoField.get(this);
		System.out.println("baseDao" + baseDao);
	}

	@Override
	public void save(T t) {
		baseDao.save(t);
	}

	@Override
	public void update(T t) {
		baseDao.update(t);
	}

	@Override
	public void delete(int id) {
		baseDao.delete(id);
	}

	@Override
	public List<T> query() {
		return baseDao.query();
	}

	@Override
	public T get(int id) {
		return (T) baseDao.get(id);
	}

}
